var validate = {
  smsTimer: '',
  warnTimer: '',
  htmlL: "<div class=\"bodybg\"></div><div class=\"prompt\"><i class=\"weui-icon-warn weui-icon_msg\"></i><div>",
  htmlL1: "<div class=\"bodybg\"></div><div class=\"prompt\"><div>",
  htmlL2: "<div class=\"bodybg\"></div><div class=\"prompt\"><i class=\"weui-icon-success weui-icon_msg\"></i><div>",
  htmlL3: "<div class=\"bodybg\"></div><div class=\"prompt\"><i class=\"weui-icon-info weui-icon_msg\"></i><div class=\"prompt_more\">",
  htmlR: "</div></div>",
  htmlR1: "</div></div>",
  htmlR3: "</div></div>",
  onlybtn: "<div class=\"weui-btn-area\"><a class=\"weui-btn weui-btn_primary\" href=\"javascript:\" id=\"onlybtn\">确定</a></div>",
  onlybtn2: "<div class=\"weui-btn-area\"><a class=\"weui-btn weui-btn_primary\" href=\"javascript:\" id=\"onlybtn2\">继续</a></div>",
  onlybtn3: "<div class=\"weui-btn-area\"><a class=\"weui-btn weui-btn_default\" href=\"javascript:\" id=\"onlybtn3\">取消</a></div>",
  productname: null,
  category: null,
  place: null,
  province: null,
  level: null,
  unit: null,
  companytype: null,
  toptips_warn: '',
  loading_toast: '',
  list_currpage: '1',
  list_allpages: '',
  list_status: '-1',
  list_sign: false, // list_sign表示是否追加html
  all_city: null, //市/区
  province_checked: null,
  city_checked: null,
  getListData: function () {},
  noMobile: "请输入您的手机号码！",
  wrongMobile: "手机号码错误，请重新输入！",
  wrongPwd: "密码长度应为6-18位，字母、数字的组合！",
  login: {
    1000: "您输入的帐号或密码有误，请重新输入！",
    1001: "请刷新页面重新登录！",
    1002: "请输入正确的手机号码！",
    1003: "账户异常,禁止登录！"
  },
  noRegistered: "此号码未在本站注册或未绑定本站帐号，请检查后重试！",
  registered: "此号码已注册，请更换手机号码或者直接登录！",
  noImgCode: "请输入图形验证码！",
  imgCodeError: "图形验证码错误！",
  noSmsCode: "请输入短信验证码！",
  smsCodeError: "短信验证码错误！",
  sendsuc: "验证码已发送！",
  setting: {
    nameErr: "请输入您的姓名！",
    idcardErr: "身份证号码有误或为空，请核对！",
    noBirthday: "出生日期不能为空！",
    noProvince: "所在省份不能为空！",
    noCity: "所在城市不能为空！",
    noAddress: "详细地址不能为空！",
    setSuc: "恭喜！个人信息修改成功！",
    setErr: "Sorry！个人信息修改失败！"
  },
  invest: {
    emptyNum: "请输入投标金额！",
    soLittle: "投标金额不能小于起投金额！",
    soless: "可投金额小于起投金额时，需一次性投满可投金额！",
  },
  recharge: "请输入正确的充值金额！",
  cash: {
    small: "提现金额最少应为100元！",
    much: "单笔提现金额最高为500万元！",
    notnum: "请输入正确的提现金额！",
    nocard: "请选择银行卡！",
  },
  bindcard: {
    noCity: "请选择开户银行所在城市！",
    noCard: "请输入您的银行卡号码！",
    wrongCard: "您输入的银行卡号错误！",
    bindErr: "Sorry，绑定银行卡失败，请重试！",
    bindSuc: "恭喜，绑定银行卡成功！",
  },
  unbindcard: {
    noCard: "请选择您要解绑的银行卡！",
    wrongCode: "短信验证码错误或为空，请检查！",
    unbindErr: "Sorry，解绑银行卡失败，请重试！",
    unbindSuc: "恭喜，解绑银行卡成功！",
  },
  changepwd: {
    complexpwd: "请输入6-18位登录密码",
    emptypwd: "请输入您现在使用的密码！",
    emptynewpwd: "请输入您的新密码！",
    emptyrepwd: "请确认您的新密码！",
    thesame: "新密码不可与旧密码相同！",
    notsize: "密码长度应为6-18位！",
    notsame: "两次密码输入不一致！",
    wrongpwd: "Sorry，登录密码修改失败！请重试。",
    successpwd: "恭喜！登录密码修改成功！请使用新密码登录。",
  },
  regular: {
    password: /(.+){6,18}$/,
    mobile: /^1[0-9]{10}$/,
    sms: /^[0-9]{6}$/,
    isBankCard: function (str) { // 验证银行卡号
      if (str == null || str == "" || str.length < 15) {
        return false;
      }
      var last = str.substr(str.length - 1, 1);
      var front_last = str.substr(0, str.length - 1);
      var front_arr = new Array();
      for (var i = front_last.length - 1; i > -1; i--) {
        front_arr.push(front_last.substr(i, 1));
      }
      var sum1 = 0,
        sum2 = 0,
        sum3 = 0;
      for (var j = 0; j < front_arr.length; j++) {
        if ((j + 1) % 2 == 1) {
          if (parseInt(front_arr[j]) * 2 < 9) {
            sum1 += parseInt(front_arr[j]) * 2;
          } else {
            var str = parseInt(front_arr[j]) * 2;
            var str1 = 1;
            var str2 = str % 10;
            sum2 += str1;
            sum2 += str2;
          }
        } else {
          sum3 += parseInt(front_arr[j]);
        }
      }
      var sum = sum1 + sum2 + sum3;
      var luhn = sum % 10 == 0 ? 0 : 10 - sum % 10;
      if (luhn == parseInt(last)) {
        return true;
      } else {
        return false;
      }
    }
  },
  toptipsWarn: function (text) {
    var that = this;
    clearTimeout(this.warnTimer)
    if (this.toptips_warn.length > 0) {
      this.toptips_warn.text(text)
    } else {
      $("body").append('<div class="toptips toptips_warn">' + text + '</div>');
      this.toptips_warn = $('.toptips');
    }
    this.warnTimer = setTimeout(function () {
      $(".toptips").remove();
      that.toptips_warn = '';
    }, 2000)
  },
  toast: function (str) {
    var $toast = $('#toast');
    if ($toast.css('display') != 'none') return;
    $toast.find(".weui-toast__content").html(str);
    $toast.fadeIn(100);
    setTimeout(function () {
      $toast.fadeOut(100);
    }, 2000);
  },
  changeCode: function (obj, page) {
    var newImg = "/Captcha?t=" + page + "&b=" + Math.random();
    $(obj).attr('src', newImg);
  },
  postAgain: function (obj, action, bool) {
    var mobile = $('#mobile').val();
    $(obj).addClass('disabled');
    var num = 120;
    $(obj).html("120秒后重发");
    validate.smsTimer = setInterval(function () {
      num--;
      if (num < 1) {
        clearInterval(validate.smsTimer);
        $(".getsms").removeClass('disabled').html("重新发送");
      } else {
        $(".getsms").html(num + "秒后重发");
      }
    }, 1000);
  },
  getSms: function (obj, action, imgcode) {
    var _that = obj;
    var mobile = $('#mobile').val();
    var imgcode = $('#imgcode').val();
    var tips = 1;
    $.ajax({
      type: "POST",
      async: false,
      dataType: "json",
      url: "/mobile/register/hasMobileCheck",
      data: {
        "mobile": mobile
      },
      success: function (data) {
        if (data.code == 1002 && action == 'register') {
          $('#msgbox').html(validate.htmlL + validate.registered + validate.htmlR);
          tips = 0;
        } else if (data.code == 1 && action == 'forgetpwd') {
          $('#msgbox').html(validate.htmlL + validate.noRegistered + validate.htmlR);
          tips = 0;
        }
      }
    });

    if (tips === 0) {
      return false;
    }
    if (imgcode.length != 4) {
      validate.toptipsWarn("请输入正确的图形验证码")
      return false;
    }

    $.ajax({
      type: "POST",
      dataType: "json",
      url: "/mobile/sms/",
      data: {
        "mobile": mobile,
        "key": imgcode,
        "action": action
      },
      success: function (data) {
        if (data.code == 1) {
          validate.postAgain(_that);
          $('#msgbox').html(validate.htmlL2 + '短信验证码发送成功！' + validate.htmlR);
        } else if (data.code == 1002) {
          validate.changeCode(".imgcode-img", action)
          validate.toptipsWarn(data.msg)
        } else {
          $('#msgbox').html(validate.htmlL + data.msg + validate.htmlR);
        }
      }
    });
  },
  clearNoNum: function (domobj) {
    domobj.value = domobj.value.replace(/(^0)|[^\d.]/g, ""); //开头是0或"数字"和"."以外的字符都清除
    domobj.value = domobj.value.replace(/^\./g, ""); //验证第一个字符是数字而不是
    domobj.value = domobj.value.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
    domobj.value = domobj.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
    domobj.value = domobj.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); //只能输入两个小数
  },
  throttle: function (fn, interval) { // 事件节流
    // last为上一次触发回调的时间
    var last = 0
    return function () {
      var context = this
      var args = arguments
      var now = +new Date()
      if (now - last >= interval) {
        // 如果时间间隔大于我们设定的时间间隔阈值，则执行回调
        last = now;
        fn.apply(context, args);
      }
    }
  },
  debounce: function (fn, delay) { // 事件防抖
    var timer = null
    // 将debounce处理结果当作函数返回
    return function () {
      var context = this
      var args = arguments
      // 每次事件被触发时，都去清除之前的旧定时器
      if (timer) {
        clearTimeout(timer)
      }
      timer = setTimeout(function () {
        fn.apply(context, args)
      }, delay)
    }
  },
  getFormatDate: function (t) { // 时间格式：yyyy-mm-dd
    var date = new Date(t);
    var seperator = "-";
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
      month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
      strDate = "0" + strDate;
    }
    var currentdate = year + seperator + month + seperator + strDate;
    return currentdate;
  },
  getFormatHms: function (t) { // 时间格式：yyyy-mm-dd hh:mm:ss
    var now = new Date(t);
    var year = now.getFullYear(); //年
    var month = now.getMonth() + 1; //月
    var day = now.getDate(); //日
    var hh = now.getHours(); //时
    var mm = now.getMinutes(); //分
    var ss = now.getSeconds(); //秒
    var clock = year + "-";
    if (month < 10) clock += "0";
    clock += month + "-";
    if (day < 10) clock += "0";
    clock += day + " ";
    if (hh < 10) clock += "0";
    clock += hh + ":";
    if (mm < 10) clock += '0';
    clock += mm + ":";
    if (ss < 10) clock += '0';
    clock += ss;
    return clock;
  },
  searchToObj: function (str) { // location.search转对象
    if (str == undefined) return;
    str = str.substr(1)
    var arr = str.split("&"),
      obj = {},
      newArr = [];
    arr.map(function (value, index, arr) {
      newArr = value.split("=")
      if (newArr[0] != undefined) {
        obj[newArr[0]] = newArr[1]
      }
    })
    return obj
  },
  selectProvinceCity: function (callback) { // 选择省市
    $.ajax({
      type: "post",
      url: "/mobile/area/getcity",
      dataType: "json",
      success: function (res) {
        if (res.code == "1") {
          validate.all_city = res.data;

          function traverse_province(province, p_val) {
            this.label = province;
            this.value = p_val;
            this.children = [];
          }

          function traverse_city(c_name, c_val) {
            this.label = c_name;
            this.value = c_val;

          }
          var arr_province = [];
          var sheng = "";
          $.each(validate.province, function (key_p, p_val) {
            sheng = new traverse_province(p_val.name, p_val.id)
            $.each(validate.all_city, function (key_c, c_val) {
              if (p_val.id == key_c) {
                $.each(c_val, function (k, vv) {
                  var o = new traverse_city(vv.name, vv.id)
                  sheng.children.push(o)
                })
                return false;
              }
            })
            arr_province.push(sheng)

          })
          $("#province-city").on("click", function (e) {
            e.preventDefault();
            weui.picker(arr_province, {
              className: 'custom-classname',
              container: '.weui-tab__panel',
              defaultValue: [19, 1601],
              onConfirm: function (result) {
                validate.province_checked = result[0].value;
                validate.city_checked = result[1].value;
                callback(result)
              },
              id: 'doubleLinePicker'
            });

          })

        }
      }
    })
  },
  loadingToast: function (text) {
    var loading_text = text ? '<p class="loading-toast-text">' + text + '</p>' : '';
    var loading_html = '<div id="loading-toast"><div class="weui-mask_transparent"></div><div class="aloding-img"><div class="flex-column"><i class="weui-loading "></i>' + loading_text + '</div></div></div>';

    $("body").append(loading_html);
  },
  loadingToastHide: function () {
    $('#loading-toast').remove();
  }



};

function addWrong(obj) {
  $(obj).parents('.weui-cell').addClass('weui-cell_warn');
}

function webBar() { //设置浮动条位置
  var wH = $(window).height();
  //	var J_webH = $('#J_webmenu').outerHeight();
  //	$('#J_webmenu').css('top', wH - J_webH);
  //	var compost_btnH = $(".compost-btn").outerHeight();
  //	$('.compost-btn').css('top', wH - compost_btnH);
  //判断是否为qq打开
  var isQQ = navigator.userAgent.toLocaleLowerCase().indexOf('qq') > -1 && navigator.userAgent.toLocaleLowerCase().indexOf('qqbrowser') < 0;
  //判断是否为首页
  var pName = location.pathname.toLocaleLowerCase();
  var isIndex = pName === '/mobile' || pName === '/mobile/' || pName.indexOf('/mobile/index') > -1;
  //判断是否为个人中心首页
  // var isCenterIndex = pName === '/mobile/center' || pName === '/mobile/center/' || pName.indexOf('/mobile/center/index') > -1;
  //隐藏头部显示
  if (isQQ || isIndex) {
    $('.header').hide();
  }
}

function isPage(page) {
  return location.pathname.indexOf(page) > -1;
}

function pathName() {
  return location.pathname;
}

/*
 * 输入框删除按钮
 */
$('.weui-icon-clear').on('mousedown', function (e) {
  e.preventDefault();
  $(this).parents('.weui-cell').find('.weui-input').val('');
  $(this).css('display', 'none');
});

$('#mobile,.weui-input').on('focus', function (e) {
  $(this).on('input', function () {
    if ($(this).val() !== '') {
      $(this).parent().siblings('.weui-icon-clear').css('display', 'block');
    } else {
      $(this).parent().siblings('.weui-icon-clear').css('display', 'none');
    }
  });
  if ($(this).val() !== '') {
    $(this).parent().siblings('.weui-icon-clear').css('display', 'block');
  }
}).on('blur', function () {
  $(this).parent().siblings('.weui-icon-clear').css('display', 'none');
});

// 固定顶部导航栏
var nav_fixed_wrap = $(".js-nav-fixed-wrap")
var nav_fixed = $(".js-nav-fixed")
if (nav_fixed_wrap.length > 0) {
  $(window).on('scroll', validate.throttle(
    function () {
      var nav_top = nav_fixed_wrap.offset().top;
      var wScroll = $(window).scrollTop();
      if (nav_top <= wScroll) {
        nav_fixed.addClass("nav-fixed")
      } else {
        nav_fixed.removeClass("nav-fixed")
      }
    }, 15))
}

// i-tabbar类下的tabbar切换
$('.i-tabbar .swiper-slide').on('click', function () {
  $(this).addClass('act').siblings().removeClass('act')
})

// $(window).on('scroll',function(){
// 	var nav_top = $(".js-nav-fixed-wrap").offset().top;
// 	console.log(nav_top)
// 	var wScroll = $(window).scrollTop();
// 	if(nav_top <= wScroll){
// 		$(".js-nav-fixed").addClass("nav-fixed")
// 	}else{
// 		$(".js-nav-fixed").removeClass("nav-fixed")
// 	}
// })

// 更改select选中后的颜色
var unSelected = "#ccc";
var selected_color2 = "#090F28";
$("select").change(function () {
  var selItem = $(this).val();
  if (selItem == $(this).find('option:first').val()) {
    $(this).css("color", unSelected);
  } else {
    $(this).css("color", selected_color2);
  }
});

/*
判断页面展示图标
*/
// function tabbarLight(index) {
//   // var _a = $('.weui-tabbar__item').eq(index).find('img');
//   var navigation_bar = '.item' + index;
//   var _a = $(navigation_bar).eq(0).find('img');
//   var _aSrc = _a.attr('src').replace('.png', '_on.png');
//   _a.attr('src', _aSrc);
// }
// if (pathName() == '/mobile') {
//   tabbarLight(0)
// } else if (isPage('/mobile/mall/category') || isPage('/mobile/mall/mindex') || (/^\/mobile\/mall$/.test(location.pathname))) {
//   tabbarLight(1)
// } else if (isPage('/mobile/buy') || isPage('/mobile/supply')) {
//   tabbarLight(2)
// } else if (isPage('/mobile/discover')) {
//   tabbarLight(3)
// } else if (pathName() == '/mobile/center' || pathName() == '/mobile/center/' || isPage('/mobile/agreement/vip') || isPage('/mobile/agreement/aftersale')) {
//   tabbarLight(4)
// }
/*选择控制开始*/
function selectContent(type, data) {
  var title = type == "1" ? "请选择品类" : type == "2" ? "请选择木材品名" : type == "3" ? "请选择木材产地" : type == "4" ? "请选择木材等级" : type == "5" ? "单位" : type == "6" ? "公司类型" : type == "7" ? "采购地区" : "请选择";
  $(".com-select-title").text(title);
  if (type == 2) {
    var _placeholder = '请输入品名';
    if ($('.com-select-search').length > 0) {
      $('.com-select-search').show().find('#select-search-input').val('');
    } else {
      $(".com-select-wrap .weui-cells").before('<div class="com-select-search"><input type="text" class="weui-input select-search-input" id="select-search-input" maxlength="10" placeholder="' + _placeholder + '"><i class="weui-icon-search"></i></div>');
    }
    selectSearch(data)
  } else {
    $('.com-select-search').remove();
  }
  var content = "";
  for (var i = 0; i < data.length; i++) {
    content += '<a class="weui-cell weui-cell_access" data-id="' + data[i].id + '" href="javascript:;"><div class="weui-cell__bd"><p>' + data[i].name + '</p></div><div class="weui-cell__ft"></div></a>';
  }
  $(".com-select-wrap").addClass("act").find(".weui-cells").html(content);
}
var select_that = null;
$("[data-select]").on("click", function (e) {
  e.preventDefault();
  $(".com-select-wrap").scrollTop(0);
  var type = $(this).data("select");
  select_that = this;
  switch (type) {
    case 1: //品类
      selectContent(type, validate.category);
      break;
    case 2: //品名
      selectContent(type, validate.productname);
      break;
    case 3: //木材产地
      selectContent(type, validate.place);
      break;
    case 4: //木材等级
      selectContent(type, validate.level);
      break;
    case 5: //单位
      selectContent(type, validate.unit);
      break;
    case 6: //公司类型
      selectContent(type, validate.companytype);
      break;
    case 7: //省
      selectContent(type, validate.province);
      break;
  }

})

$(".com-select-wrap").on("click", ".weui-cell", function (e) {
  e.preventDefault();
  var _id = $(this).data("id");
  var text = $(this).find(".weui-cell__bd").find("p").text();
  $(select_that).data("id", _id).find(".com-selected-c").addClass("act").text(text);
  $(".com-select-wrap").removeClass("act");
  if ($(select_that).data("select") == "5") {
    $(".js-p-unit").html(text)
  }
}).on("swipeLeft", function (e) {
  e.preventDefault();
  $(this).removeClass("act");
})

$(".select-wrap-close").on("click", function () {
  $(this).parents(".com-select-wrap").removeClass("act");
})

function selectSearch(data) {
  $(".select-search-input").on("input", validate.throttle(function () {
    var _productname = $(this).val();
    var search_html = "";
    if (_productname == '') {
      var content = "";
      for (var i = 0; i < data.length; i++) {
        content += '<a class="weui-cell weui-cell_access" data-id="' + data[i].id + '" href="javascript:;"><div class="weui-cell__bd"><p>' + data[i].name + '</p></div><div class="weui-cell__ft"></div></a>';
      }
      $(".com-select-wrap .weui-cells").html(content);
      $('.select-search-no').hide();
    } else {
      for (var i = 0; i < data.length; i++) {
        if (data[i].name.indexOf(_productname) > -1) {
          search_html += '<a class="weui-cell weui-cell_access" data-id="' + data[i].id + '" href="javascript:;"><div class="weui-cell__bd"><p>' + data[i].name + '</p></div><div class="weui-cell__ft"></div></a>'
        }
      }
      var $search_no = '';
      if (search_html == '') {
        $search_no = $('.select-search-no');
        if ($search_no.length > 0) {
          $search_no.show();
        } else {
          $(".com-select-wrap .weui-cells").after('<div class="select-search-no">无匹配项</div>');
        }
      } else {
        $('.select-search-no').hide();
      }
      $(".com-select-wrap .weui-cells").html(search_html);
    }

  }, 150))
}
/*选择控制结束*/


$(".g-mask").on("click", function () {
  $(this).css("z-index", "4").hide();
  $("body,html").removeClass("overflow-h");
  $(".js-bmodal").removeClass("act");
  $(".js-smodal").hide();
  $(".js-smodalbtn-wrap .js-smodalbtn").removeClass("act");
  $(".js-bpopup,.js-t-bpopup").removeClass("act");
})
$(".js-smodalbtn-wrap .js-smodalbtn").on("click", function (e) {
  e.preventDefault();
  if ($(this).hasClass("act")) {
    $(this).removeClass("act")
    $(".g-mask").hide();
    $("body,html").removeClass("overflow-h");
    $(".js-smodal-wrap .js-smodal").hide();
    return;
  }
  var index = $(".js-smodalbtn-wrap .js-smodalbtn").index(this);
  $(".g-mask").show();
  $("body,html").addClass("overflow-h");
  $(this).addClass("act").siblings(".js-smodalbtn").removeClass("act");
  $(".js-smodal-wrap .js-smodal").eq(index).show().siblings(".js-smodal").hide();
})
$(".js-bmodalbtn").on("click", function (e) {
  e.preventDefault();
  $(".js-smodalbtn-wrap .js-smodalbtn").removeClass("act");
  $(".js-smodal").hide();
  $(".js-bmodal").addClass("act");
  $(".g-mask").css("z-index", "1002").show();
  $("body,html").addClass("overflow-h");
})
$(".pack-toggle").on("click", function () {
  if ($(this).hasClass("act")) {
    $(this).find(".pack-title").html("收起");
    $(this).find(".iconfont").html("&#xe6bd;");
    $(this).removeClass("act");
  } else {
    $(this).find(".pack-title").html("展开");
    $(this).find(".iconfont").html("&#xe6be;");
    $(this).addClass("act");
  }
  $(this).parents(".t-body").find("ul").toggleClass("act");
})
$(".js-bpopup-btn").on("click", function (e) {
  e.preventDefault();
  $(".g-mask").css("z-index", "1002").show();
  $(".js-bpopup").addClass("act");

  //	$(".bpopup-wrap-area").css("display","block");
  //	setTimeout(function(){
  //		$(".js-bpopup").addClass("act");
  //	},0)
  //

})
$(".js-bpopup-close").on("click", function (e) {
  e.preventDefault();
  $(".g-mask").css("z-index", "4").hide();
  $(".js-bpopup").removeClass("act");
})

/*tab标签页切换*/
$('.tabbar-header-wrap div').on('click', function () {
  var _index = $(this).index();
  $(this).addClass('act').siblings().removeClass('act');
  $('.tabbar-body').eq(_index).show().siblings().hide();
})

/*眼睛*/
$('.input-eye').on('click', function (event) {
  event.preventDefault();
  var canSee = $(this).hasClass('eye-on');
  if (!canSee) {
    $(this).addClass('eye-on').parent().find(".weui-input").attr('type', 'text');
  } else {
    $(this).removeClass('eye-on').parent().find(".weui-input").attr('type', 'password');
  }
})

/*用户列表展示*/
if (isPage('/mobile/customer/specproduct') || isPage('/mobile/customer/buyback') || isPage('/mobile/merchant/backlist') || isPage('/mobile/merchant/specproduct') || isPage('/mobile/merchant/ptorder') || isPage('/mobile/merchant/myorder') || isPage('/mobile/merchant/quote') || isPage('/mobile/customer/myorder') || isPage('/mobile/customer/ptproductorder')) {
  $('.warpper').css('height', 'auto');
  var lodaing_html = '<div id="ajaxloading" class="hide"><div class="weui-mask_transparent"></div><div class="aloding-img" ><i class="weui-loading"></i></div></div>';
  $(document).ajaxStart(function () {
    var $ajaxloading = $('#ajaxloading');
    if ($ajaxloading.length > 0) {
      $ajaxloading.show();
    } else {
      $('body').append(lodaing_html)
    }
  });
  $(document).ajaxComplete(function () {
    $('#ajaxloading').hide();
  });

  function userDataList(opts) {
    opts = opts || {};
    validate.list_currpage = opts.curr_p || 1;
    validate.list_status = opts.status || -1;
    validate.list_sign = opts.sign || false;
    validate.getListData();
  }

  $('.spec-list-bar').on('click', function (e) {
    e.preventDefault();
    validate.list_status = String($(this).data('state'));
    userDataList({
      curr_p: 1,
      status: validate.list_status,
      sign: true
    })
  })

  //下滑加载更多
  function moreSroll() {
    if (validate.list_currpage <= validate.list_allpages) {
      var wH = $(window).height();
      var wScroll = $(window).scrollTop();
      var totalheight = parseFloat(wH) + parseFloat(wScroll);
      if ($(document).height() <= totalheight + 60) {
        userDataList({
          curr_p: validate.list_currpage,
          status: validate.list_status,
          sign: false
        })
      }
    }
  }

  $(window).on('scroll', validate.debounce(moreSroll, 400));
}


$(function () {
  webBar();
  $('.weui-input').each(function (index, el) {
    $(this).parents('.weui-cell').removeClass('weui-cell_warn');
  });
  $('#msgbox').on('click', '.bodybg,.modal-close,#onlybtn', function (event) { //隐藏弹窗提示信息
    event.preventDefault();
    event.stopPropagation();
    $(this).parents("#msgbox").empty();
  });

  //20170523 资料空白新
  if (isPage('/help/list') || isPage('/help/view')) {
    $('.answer img').each(function (index, el) {
      //修复异常
      var oriSc = $(this).attr('src');
      if (oriSc.indexOf("http") < 0) {
        $(this).attr('src', IMG_URL + oriSc);
      }
    });
  }

  /**
   *图片验证码刷新
   **/
  $('.loadcode').on('click', function (event) {
    event.preventDefault();
    mobileCommon.getImg(this, $(this).data('type'));
  });

  /**
   *点击关闭警告窗
   **/
  $('body').on('click', '.weui-toptips', function () {
    $(this).remove();
  })
});

//mobile 
mobileCommon = {
  /**
   * [setCookie 设置cookie]
   */
  setCookie: function (key, value, t) {
    var millisecond = new Date().getTime();
    var expiresTime = new Date(millisecond + t * 1000 * 60);
    Cookies.set(key, value, {
      expires: expiresTime,
    })
  },
  /**
   * [getCookie 获取cookie]
   */
  getCookie: function (key) {
    return Cookies.get(key);
  },
  /**
   * [removeCookie 移除cookie]
   */
  removeCookie: function (key) {
    Cookies.remove(key);
  },
  /**
   * [removeCookies 移除多个cookie]
   */
  removeCookies() {
    for (var i in arguments) {
      Cookies.remove(arguments[i])
    }
  },
  //获取验证码时间间隔限制
  getCooling: function (elem, t, text) {
    var time = t;
    elem.attr('disabled', "true").html(time + "秒后重发");
    var timer = setInterval(function () {
      time--;
      if (time === 0) {
        clearInterval(timer);
        elem.html(text);
        elem.removeAttr("disabled");
      } else {
        elem.html(time + "秒后重发");
      }
    }, 1000)
  },

  //倒计时执行
  countdownToDo: function (elem, callback) {
    var $this = $(elem);
    var ntime = 5;
    var timer = setInterval(function () {
      ntime--;
      if (ntime > 0) {
        $this.html(ntime + "秒");
      } else {
        callback()
      }
    }, 1000);
  },

  // 触底加载
  touchBottomLoad: function (elem, callback) {
    var viewH = elem.height(),
      contentH = elem.get(0).scrollHeight,
      scrollTop = elem.scrollTop();
    if (scrollTop / (contentH - viewH) >= 1) {
      callback()
    }
  },

  //获取url参数
  getQueryString: function (name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
  },

  //保留两位小数并不四舍五入
  retainTwo: function (num) {
    return (Math.floor(num * 100) / 100).toFixed(2);
    // return parseFloat((Math.floor(num * 100) / 100).toFixed(2)); //优化后方法
  },

  //金额输入正则
  testAmount: function (elem) {
		//禁止录入整数部分两位以上，但首位为0
		elem.value = elem.value.replace(/^([1-9]\d*(\.[\d]{0,2})?|0(\.[\d]{0,2})?)[\d.]*/g, '$1');
		//禁止录入整数部分超过6位
		// elem.value = elem.value.replace(/^([1-9]\d{5})\d*/g, '$1');
		//替换除了数字和.以外的字符
		elem.value = elem.value.replace(/[^\d\.]/g, '');
		//第一个输入.  则自动变为0.
		elem.value = elem.value.replace(/^\./g, '0.');
		//保证.只出现一次，而不能出现两次以上 2..    2.2.2
		elem.value = elem.value.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.');
		//只能输入两个小数
		elem.value = elem.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');
  },
  //数组正则 
  onlyNumReg: function (str) {
    return str.replace(/[^\d]/g, '')
  },

  //上传图片
  uploadImg: function (element, tag) {
    var file = tag.files[0];
    var imgSrc;
    if (!/image\/\w+/.test(file.type)) {
      return false;
    }
    var reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function () {
      imgSrc = this.result;
      $(element).attr('src', imgSrc)
    };
  },
  /**
   ** 获取验证码
   ** [倒计时元素$('') 获取验证码接口 String ,参数 String ,回调函数 Function,回调函数（else code码负责处理时调用） Function]
   **/
  getVcode: function (elem, url, field, callback) {
    var loading = weui.loading();
    $.ajax({
      url: url,
      dataType: 'json',
      type: 'POST',
      data: field,
      success: function (res) {
        if (res.code == 1) {
          weui.toast(res.msg);
          mobileCommon.getCooling(elem, 60, '获取验证码');
        }
        callback(res)
      },
      complete: function () {
        loading.hide();
      }
    })
  },

  //获取参数值
  getQueryString: function (e) {
    var t = new RegExp("(^|&)" + e + "=([^&]*)(&|$)", "i"),
      n = window.location.search.substr(1).match(t);
    return null != n ? unescape(n[2]) : null
  },
  //功能待开发
  waitExploit: function () {
    weui.topTips('功能优化中，敬请期待')
  },
  //精选T、精选C图标初始化
  initTitleIcon: function () {
    $('.icon-select-normal').html('精选/C')
    $('.icon-select-limit').html('<span>限</span><span>精选/C</span>')
    $('.icon-select-limitT').html('<span>限</span><span>精选/T</span>')
  },
  //补零 (数值、位数)
  zeroize: function (num, digit) {
    digit = digit || 2;
    var len = num.toString().length;
    while (len < digit) {
      num = '0' + num;
      len = num.toString().length;
    }
    return num;
  },
  //检测是否为今天
  testToday: function (day) {
    var date = new Date();
    var y = date.getFullYear();
    var m = mobileCommon.zeroize(date.getMonth() + 1, 2);
    var d = mobileCommon.zeroize(date.getDate(), 2);
    var _date = new Date(day);
    var _y = _date.getFullYear();
    var _m = mobileCommon.zeroize(_date.getMonth() + 1, 2);
    var _d = mobileCommon.zeroize(_date.getDate(), 2);
    return (y + '-' + m + '-' + d) == (_y + '-' + _m + '-' + _d) ? '今天' : (_y + '-' + _m + '-' + _d)
  },
  //获取多种产品属性值
  getProductAttr: function (type, callback) {
    var typeField = {
      category: 0,
      level: 0,
      name: 0,
      place: 0,
      unit: 0,
      house: 0,
      purchase_type: 0
    }
    var typeName = {
      category: '品类',
      level: '等级',
      name: '品名',
      place: '产地',
      unit: '单位',
      house: '仓库',
      purchase_type: '仓库'
    }
    var dataName = {
      category: 'category_name',
      level: 'level_name',
      name: 'product_name',
      place: 'place_name',
      unit: 'unit_name',
      house: 'house_name',
      purchase_type: 'house_name'
    }

    var field = {};
    field = $.extend({}, field, typeField);
    field[type] = 1;

    var loading = weui.loading()
    $.ajax({
      url: '/mobile/utils/getProductAttribute',
      dataType: 'json',
      type: 'POST',
      data: field,
      success: function (res) {
        if (res.code == 1) {
          var list = res.data[type];
          callback(list, typeName[type], dataName[type]);
        } else {
          weui.topTips(res.msg);
        }
      },
      complete: function () {
        loading.hide()
      }
    })
  },

  //倒计时
  countdown: function (d, format) {
    var _d = (new Date(d).getTime() - new Date().getTime()) / 1000;
    if (_d <= 0) {
      return false;
    }
    var dObj = {}
    var $min = 60,
      $hour = 60 * $min,
      $day = 24 * $hour,
      $mon = 30 * $day,
      $year = 365 * $day;


    var mat = format.split('-'),
      str = '';
    mat.map((item) => {
      if (item == 'YY') {
        initNum(dObj);
        dObj.Y = mobileCommon.zeroize(Math.floor(_d / $year));
        return dObj.Y + '年'
      } else if (item == 'MM') {
        initNum(dObj);
        dObj.M = mobileCommon.zeroize(Math.floor((_d - dObj.Y * $year) / $mon));
        return dObj.M + '月'
      } else if (item == 'DD') {
        initNum(dObj);
        dObj.D = mobileCommon.zeroize(Math.floor((_d - dObj.Y * $year - dObj.M * $mon) / $day));
        return dObj.D + '天'
      } else if (item == 'hh') {
        initNum(dObj);
        dObj.h = mobileCommon.zeroize(Math.floor((_d - dObj.Y * $year - dObj.M * $mon - dObj.D * $day) / $hour));
        return dObj.h + '时'
      } else if (item == 'mm') {
        initNum(dObj);
        dObj.m = mobileCommon.zeroize(Math.floor((_d - dObj.Y * $year - dObj.M * $mon - dObj.D * $day - dObj.h * $hour) / $min));
        return dObj.m + '分'
      } else if (item == 'ss') {
        initNum(dObj);
        dObj.s = mobileCommon.zeroize(Math.floor(_d - dObj.Y * $year - dObj.M * $mon - dObj.D * $day - dObj.h * $hour - dObj.m * $min));
        return dObj.s + '秒'
      } else {
        return ''
      }
    }).forEach((item) => {
      str += item
    })
    return str
    //数值不存在时设为0
    function initNum(obj) {
      obj = $.extend(obj, {
        Y: dObj.Y || 0,
        M: dObj.M || 0,
        D: dObj.D || 0,
        h: dObj.h || 0,
        m: dObj.m || 0,
        s: dObj.s || 0,
      })
    }
  },

  //点击刷新图形验证码
  getImg: function (elem, action) {
    var newImg = "/mobile/utils/captcha?t=" + action + "&b=" + Math.random();
    $(elem).attr('src', newImg);
  },
  //图形验证码验证
  captchaCheck: function (code, type, callback) {
    reg = {
      code: /[a-zA-Z0-9]{4}/
    };
    if (!reg.code.test(code)) {
      if (code === '') {
        weui.topTips('请输入图形验证码');
        return false;
      } else {
        weui.topTips('图形验证码格式错误');
        return false;
      }
    }
    data = {
      code: code,
      type: type,
    };

    var loading = weui.loading();
    $.ajax({
      async: false,
      url: '/mobile/utils/captchaCheck',
      dataType: 'json',
      type: 'POST',
      data: data,
      success: function (res) {
        if (res.code == 1) {
          callback();
          return true;
        } else {
          weui.topTips(res.msg);
          return false;
        }
      },
      complete: function () {
        loading.hide()
      }
    })
  },
  checkIsPhone: function (phone) {
    reg = {
      mobile: /^1[3|4|5|6|7|8|9][0-9]{9}$/,
    };
    if (!reg.mobile.test(phone)) {
      if (phone === '') {
        weui.topTips('请输入手机号码');
        return false;
      } else {
        weui.topTips('手机号码格式错误');
        return false;
      }
    } else {
      return true;
    }
  },
  //实名认证提示弹框
  attestTips: function (code) {
    //code=1代表已实名认证
    if (code != 1) {
      var str = '';
      str += '<img src="/res/mobile/images/member/icon-smrz.png" class="icon size6">';
      str += '<div class="content tx1">为了保证您的各项权益<br>请通过实名认证绑定账户</div>';
      str += '<p class="tips"><a href="/mobile/index/index">暂不认证</a><a href="/mobile/wechat/userlist">切换账号</a></p>';
      // 弹出需要认证弹窗
      weui.alert(str, {
        className: 'alert-form tips-form',
        buttons: [{
          label: '立即认证',
          type: 'primary',
          onClick: function () {
            window.location.href = '/mobile/identify/index'
          }
        }],
      })
    }
  },
  //如果返回状态码是1003，提示后，自动1秒跳转登录页面
  loginTips: function (code, msg) {
    if (code == 10003) {
      msg = msg ? msg : '请重新登录';
      weui.topTips(msg, function () {
        window.location.href = '/mobile/auth/login';
      });
      return true;
    } else {
      return false;
    }
  },
  // 解决苹果输入后不回弹页面
  initIOSInput: function () {
    var u = navigator.userAgent,
      app = navigator.appVersion
    var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
    $(document).ready(function () {
      $("input").blur(function () {
        if (isIOS) {
          blurAdjust()
        }
      });
    });
    // 解决苹果不回弹页面
    function blurAdjust(e) {
      setTimeout(() => {
        if (document.activeElement.tagName == 'INPUT' || document.activeElement.tagName == 'TEXTAREA') {
          return
        }
        let result = 'pc';
        if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) { //判断iPhone|iPad|iPod|iOS
          result = 'ios'
        } else if (/(Android)/i.test(navigator.userAgent)) { //判断Android
          result = 'android'
        }

        if (result = 'ios') {
          document.activeElement.scrollIntoViewIfNeeded(true);
        }
      }, 100)
    }
  },
}
mobileCommon.initIOSInput();

function swiperScroll(loadCallback, elem) {
  var elem = elem || '.swiper-scroll';
  var mySwiper = new Swiper(elem, {
    direction: 'vertical',
    scrollbar: '.swiper-scrollbar',
    slidesPerView: 'auto',
    mousewheelControl: true,
    freeMode: true,
    on: {
      touchMove: function (swiper) { //手动滑动中触发
        var _viewHeight = $(elem).find('.swiper-wrapper').height()
        var _contentHeight = $(elem).find('.swiper-slide').height()
        var _touchend = _viewHeight - _contentHeight;
        var _deltaHeight = 50;
        if (_contentHeight >= _viewHeight) {
          $(elem).find('.load-more-wrapper').show();
          console.log($(elem).find('.load-more-text'))
          if (mySwiper.translate <= _touchend && mySwiper.translate > _touchend - _deltaHeight && mySwiper.translate < 0) {
            $(elem).find('.load-more-text').text('下拉加载更多');
          } else if (mySwiper.translate <= _touchend - _deltaHeight && mySwiper.translate < 0) {
            $(elem).find('.load-more-text').text('释放加载更多');
          }
        }
      },
      touchEnd: function (swiper) {
        var _viewHeight = $(elem).find('.swiper-wrapper').height()
        var _contentHeight = $(elem).find('.swiper-slide').height()
        var _touchend = _viewHeight - _contentHeight;
        var _deltaHeight = 50;
        if (_contentHeight >= _viewHeight) {
          // 上拉加载
          if (mySwiper.translate <= _touchend - _deltaHeight && mySwiper.translate < 0) {
            if (loadCallback) {
              loadCallback();
            }
          } else if (mySwiper.translate < 0 && mySwiper.translate > _touchend - _deltaHeight) {

          }
          return false;
        }
      }
    }
  });
  return mySwiper;
}